package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.pojo.PageResult;
import cn.itcast.hotel.pojo.RequestParam;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.lucene.search.function.CombineFunction;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {

    @Autowired
    private RestHighLevelClient client;

    @Override
    public PageResult search(RequestParam requestParam) {

        //1.创建请求对象
        SearchRequest searchRequest=new SearchRequest("hotel");

        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

        //2.设置请求参数
        if(StringUtils.isBlank(requestParam.getKey())){
            //2.1请求类型-查询全部
            boolQueryBuilder.must(QueryBuilders.matchAllQuery());
        }else {
            //2.1请求类型-关键词全文检索查询
            boolQueryBuilder.must(QueryBuilders.matchQuery("name",requestParam.getKey()));
        }

        //设置其他请求参数，添加组合过滤条件

        //根据品牌过滤查询
        if(StringUtils.isNotBlank(requestParam.getBrand())){
            boolQueryBuilder.filter(QueryBuilders.termQuery("brand", requestParam.getBrand()));
        }

        //根据城市过滤查询
        if(StringUtils.isNotBlank(requestParam.getCity())){
            boolQueryBuilder.filter(QueryBuilders.termQuery("city", requestParam.getCity()));
        }

        //根据星级过滤查询
        if(StringUtils.isNotBlank(requestParam.getStarName())){
            boolQueryBuilder.filter(QueryBuilders.termQuery("starName", requestParam.getStarName()));
        }

        //根据价格范围查询
        if (requestParam.getMinPrice()!=null){
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte(requestParam.getMinPrice()));
        }
        if (requestParam.getMaxPrice()!=null){
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").lte(requestParam.getMaxPrice()));
        }

        //算分函数查询：三要素-原始查询条件、过滤条件和算分函数的权重、加权模式
        FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(
                boolQueryBuilder, //原始查询条件（布尔组合查询）
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                QueryBuilders.termQuery("isAD", true), //过滤条件
                                ScoreFunctionBuilders.weightFactorFunction(10) //算分函数的权重
                        )
                });
        functionScoreQueryBuilder.boostMode(CombineFunction.MULTIPLY); //加权模式：乘法

        searchRequest.source().query(functionScoreQueryBuilder);//算分函数查询

        //2.2结果类型-分页
        int page = requestParam.getPage();//页码
        int size = requestParam.getSize();//每页查询条数
        int from = (page-1) * size;
        searchRequest.source().from(from).size(size);

        //2.3结果类型-排序（根据酒店到我的定位坐标，由近及远排序）
        if(StringUtils.isNotBlank(requestParam.getLocation())){
            searchRequest.source().sort(SortBuilders
                    .geoDistanceSort("location", new GeoPoint(requestParam.getLocation()))//排序字段
                    .order(SortOrder.ASC)//排序方向（由近及远）
                    .unit(DistanceUnit.KILOMETERS)//距离单位
            );
        }

        //3.发起搜索请求
        try {
            SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

            //4.解析响应结果（从外到内，逐层解析）
            //4.1获取搜索命中的结果对象（一级对象）
            SearchHits searchHits = searchResponse.getHits();

            //4.2获取总记录数
            long total = searchHits.getTotalHits().value;

            //4.3获取搜索命中的文档对象数组（二级对象）
            SearchHit[] hits = searchHits.getHits();

            //4.4遍历获取每个酒店的JSON文档数据并转为酒店对象数据，然后封装酒店对象集合
            List<HotelDoc>hotels=new ArrayList<>();
            for (SearchHit hit : hits) {
                String hotelDocJson = hit.getSourceAsString();//获取每个酒店的JSON文档数据
                HotelDoc hotelDoc = JSON.parseObject(hotelDocJson, HotelDoc.class);//转为酒店对象数据

                //解析结果里，酒店和我的定位坐标的距离KM数
                Object[] distances = hit.getSortValues();
                if(distances!=null && distances.length>0){
                    Object distance = distances[0];
                    hotelDoc.setDistance(distance);
                }
                hotels.add(hotelDoc);

            }

            //5.分装分页响应结果对象
            return PageResult.of(total, hotels);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
